package com.youku.compiler;

import com.youku.ast.AssignAst;
import com.youku.ast.Ast;
import com.youku.ast.BlockAst;
import com.youku.scope.GlobalScope;
import com.youku.scope.LocalScope;
import com.youku.scope.Scope;
import com.youku.scope.VariableSymbol;

public class ScopeTreeBuilder {

	private Ast ast;

	private Scope scope;

	public ScopeTreeBuilder(Parser parser) {
		super();
		this.ast = parser.tree();
	}

	public void buildTree() {

		scope = build(ast);
	}

	private Scope build(Ast ast) {
		Scope s = new GlobalScope();

		scanTree(ast, s);

		return s;
	}

	private void scanTree(Ast ast, Scope s) {

		if (ast instanceof AssignAst) {
			AssignAst assign = (AssignAst) ast;
			s.def(new VariableSymbol(assign.varValue(), s));
		} else if (ast instanceof BlockAst) {
			s = new LocalScope(s);
		}

		for (Ast child : ast.children()) {
			scanTree(child, s);
		}
		print(ast.getClass().getName());

	}

	private void print(Object o) {
		System.out.println(o);
	}
}
